import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/Main/FleetManagement/MyFleet.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/ShowDialog.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import 'package:platform/platform.dart';

class AssignDrivers extends StatefulWidget {
  const AssignDrivers({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<AssignDrivers> createState() => _AssignDriversState();
}

class _AssignDriversState extends State<AssignDrivers> {
  int pageNum=1;
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    super.initState();
    getDriversAction();
  }
  List dataList=[];
  void searchDriverAction(String text){
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/fleet/user/driverPage",
      {'current':1,"size":20,"captainId":"1781255212293775361","realName":text},
          (responseData)  {
        setState(() {
            dataList=responseData['data']['records'];

        });

      },
    );
  }
  Future<void> getDriversAction() async {
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/fleet/user/driverPage",
      {'current':pageNum,"size":20,"captainId":"1781255212293775361"},
          (responseData)  {
        setState(() {
          if(pageNum==1){
            dataList=responseData['data']['records'];
          }else{
            dataList.addAll(responseData['data']['records']);
          }

        });

      },
    );
  }
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  Future _onRefresh() async {

    pageNum=1;
    getDriversAction();

  }
  Future<void> _loadMoreData() async {

      if (dataList.length > 20*pageNum-1 ){
        pageNum=pageNum+1;
        getDriversAction();
      }



  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("分配司机",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          GestureDetector(
            child: Text("管理   ",style: TextStyle(color: Colors.black),),
            onTap: (){
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) {
                    return MyFleet(captainId: '1781255212293775361',
                    );
                  }));
            },
          ),
        ],
      ),
      body: ListView(
        children: [
          Container(
            child: BrnSearchText(
              focusNode: focusNode,
              controller: textController,
              searchController: scontroller..isActionShow = false,
              outSideColor:MyColors.backgreyColor,
              innerColor:Colors.white,
              borderRadius:BorderRadius.all(const Radius.circular(10.0)),
              hintText:"搜索司机",
              onTextClear: () {
                debugPrint('sss');
                return false;
              },
              autoFocus: false,
              onActionTap: () {
                scontroller.isClearShow = false;
                scontroller.isActionShow = false;
                focusNode.unfocus();

              },
              onTextCommit: (text) {

              },
              onTextChange: (text) {
                if(text!="") {
                  searchDriverAction(text);
                }else{
                  getDriversAction();
                }
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 27.w),
            child:  Row(
              children: [
                Text(widget.dataMap['vehicleNum'].toString(),style: TextStyle(color: Colors.black),),
                SizedBox(width: 8.w,),
                Text(widget.dataMap['vehicleLength'].toString()+"米/"+widget.dataMap['vehicleModel'].toString(),style: TextStyle(color: MyColors.textColor,fontSize: 12.sp,)),
              ],
            ),
          ),
          EasyRefresh(
          header:
          ClassicHeader(
          dragText: '下拉刷新',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '刷新成功',
          noMoreText: '暂无更多',
          failedText: '刷新失败',
          messageText: '刷新时间 %T',
          ),

          footer: ClassicFooter(
          dragText: '加载更多',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '加载成功',
          noMoreText: '暂无更多',
          failedText: '加载失败',
          messageText: '加载时间 %T',
          ),
          onRefresh: _onRefresh,
          onLoad: dataList.length > 20*pageNum-1?_loadMoreData:null,
          child:
          Container(
            margin: EdgeInsets.only(left: 10.w,right: 10.w),
            height: screenSize.height-140.h,
            child: ListView.builder(
                shrinkWrap:false,
                itemCount:dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    decoration: BoxDecoration(
                        color:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    margin: EdgeInsets.only(top: 4.h),
                    padding: EdgeInsets.only(left: 14.w,top: 12.h,right:6.w,bottom: 8.h ),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  width:30.w,
                                  height: 30.h,
                                  child:  dataList[index]['avatarPath']!=null&&dataList[index]['avatarPath']!=""?
                                  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: NetworkImage(MyServiceUrl.imgHeader +dataList[index]['avatarPath']),
                                  )
                                      :  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                                  ),
                                ),
                                SizedBox(width: 4.w,),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                    Text(dataList[index]['phoneNum'],style: TextStyle(fontSize: 12.sp,color: MyColors.textColor),),

                                  ],
                                ),
                              ],
                            ),
                            Container(
                              height: 25.h,
                              child: Row(
                                children: [
                                  GestureDetector(
                                    child:BrnTagCustom.buildBorderTag(
                                      tagText: '联系他',
                                      textColor: MyColors.themeColor,
                                      borderColor: MyColors.themeColor,
                                      borderWidth: 1,
                                      fontSize: 12.sp,
                                      tagBorderRadius: BorderRadius.all( Radius.circular(30)),
                                      textPadding: EdgeInsets.only(top: 2.h,bottom: 2.h,left: 8.w,right: 8.w),
                                    ),
                                    onTap: (){
                                      _makePhoneCall(dataList[index]['drvPhone']);
                                    },
                                  ),

                                  SizedBox(width: 8.w,),
                                  GestureDetector(
                                    child: BrnTagCustom(
                                      tagText: "分配接单",
                                      textColor: Colors.white,
                                      backgroundColor: MyColors.themeColor,
                                      tagBorderRadius: BorderRadius.all( Radius.circular(30)),
                                      fontSize: 12.sp,
                                      textPadding: EdgeInsets.only(top: 2.h,bottom: 2.h,left: 4.w,right: 4.w),
                                    ),
                                    onTap: (){
                                      Navigator.pop(context,dataList[index]);
                                    },
                                  ),
                                ],
                              ),
                            ),

                          ],
                        ),
                        Row(
                          children: [
                            Text("身份认证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                            (dataList[index]['personalStatus']==0||dataList[index]['personalStatus']==3)?

                            Icon(Icons.
                            error_outline,color: Colors.red,size: 12,)
                                :dataList[index]['personalStatus']==1?

                            Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                :
                            Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                            SizedBox(width: 8.w,),
                            Text("驾驶证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                            (dataList[index]['driverLicenseStatus']==0||dataList[index]['driverLicenseStatusdriverLicenseStatus']==3)?

                            Icon(Icons.
                            error_outline,color: Colors.red,size: 12,)
                                :dataList[index]['driverLicenseStatus']==1?

                            Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                :
                            Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                            SizedBox(width: 8.w,),
                            Text("从业资格证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                            (dataList[index]['qualificationCertificateStatus']==0||dataList[index]['qualificationCertificateStatus']==3)?

                            Icon(Icons.
                            error_outline,color: Colors.red,size: 12,)
                                :dataList[index]['qualificationCertificateStatus']==1?

                            Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                :
                            Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),


                          ],
                        ),
                      ],
                    )

                  );
                }
            ),
          )),
        ],
      ),
    );
  }
}
